<template>
  <div class="chart">
    <div v-if="false">{{test}}</div>
    <div class="content">
      <div class="btn-group btn-group-justified">
        <div class="btn-group">
          <button type="button" class="btn threeMonth" :class="showMonth?'active':''" data-interval="threeMonth"
                  @click.stop.prevent="clickMonth">最近三个月
          </button>
        </div>
        <div class="btn-group">
          <button type="button" class="btn oneYear" :class="showMonth?'':'active'" data-interval="oneYear"
                  @click.stop.prevent="clickYear">最近一年
          </button>
        </div>
      </div>

      <div class="tips" v-show="!showCanvas">
        <div class="content">{{error}}</div>
      </div>

      <canvas id="canvas" width="300" height="200" v-show="showCanvas" ref="canvas"></canvas>

      <div class="legend">
        <div>
          <span>●</span>
          &nbsp;{{userType == 'self'?'我的收益':(userType == 'other'?'TA的收益':'组合的收益')}}
        </div>
        <div>
          <span>●</span>
          &nbsp;沪深300指数
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import RemoteDAO from 'common/remoteDAO'
  import CommonUtil from 'common/common.util'
  import LocalDAO from 'common/localDAO'
  import Constant from 'common/constant'
  import Chart from 'assets/lib/chart/chart'
  import _ from 'underscore'
  import $ from 'jquery'

  export default {
    data () {
      return {
        showMonth: true,//true为显示月曲线不显示年曲线，false则相反
        showCanvas: false,// true则显示曲线图 不显示文字提示
        threeMonthData: {},
        oneYearData: {},
        error: '数据加载中',
        test: 'TEST'
      }
    },
    props: {
      userCode: {
        type: String
      },
      clientId: {
        type: String
      },
      userType: {
        type: String
      },
      groupId: {
        type: String
      },
      entrustType: {
        type: String
      }
    },
    mounted: function () {
      this.fetchThreeMonthData();
      this.fetchOneYearData();
    },
    watch: {
      'showMonth': function () {
        if (this.showMonth && !_.isEmpty(this.threeMonthData)) {
          this.createChart(this.threeMonthData);
        } else if (!this.showMonth && !_.isEmpty(this.oneYearData)) {
          this.createChart(this.oneYearData);
        }
      },
      'clientId':function (){
        //跳转相同页面，组件不重新构建，无法调用created,故需监听
        this.showMonth = true;
        this.fetchThreeMonthData();
        this.fetchOneYearData();
      }
    },
    methods: {
      clickMonth(){
        this.showMonth = true;
        //个人详情点击三月曲线标签埋点
        if (this.groupId == '') {
          var kv = {"usercode": this.userCode, "k2": ""};
          TDAPP.onEvent("15011", "", kv);
          TDAPP.send();
        }
      },
      clickYear(){
        this.showMonth = false;
        //个人详情点击一年曲线标签埋点
        if (this.groupId == '') {
          var kv = {"usercode": this.userCode, "k2": ""};
          TDAPP.onEvent("15012", "", kv);
          TDAPP.send();
        }
      },
      createChart(data){
        this.error = '数据加载中';
        if (data.labels.length == 0) {
          this.error = '暂无数据';
          this.showCanvas = false;
        } else {
            this.showCanvas = true;
            this.$nextTick(function () {
              $("#canvas").remove();
              $(".chart .legend").before('<canvas id="canvas" width="300" height="200"></canvas>');
              var ctx = document.getElementById("canvas").getContext("2d");
              var chart = new Chart(ctx);
              chart.Line(data,
                {
                  pointDot: false,
                  scaleLabel: "<%= value + '%' %>",
                  // animation : false,
                  multiTooltipTemplate: "<%= datasetLabel %>:<%= value + '%' %>"
                }
              );
            })
        }
      },
      fetchThreeMonthData(){
        var threeMonthArgs = {};
        threeMonthArgs.userType = this.userType;
        threeMonthArgs.groupId = this.groupId;
        threeMonthArgs.dataType = "0";
        threeMonthArgs.entrustType = this.entrustType;
        threeMonthArgs.clientId = this.clientId;
        this.fetchData(threeMonthArgs);
      },
      fetchOneYearData(){
        var oneYearArgs = {};
        oneYearArgs.userType = this.userType;
        oneYearArgs.groupId = this.groupId;
        oneYearArgs.dataType = "1";
        oneYearArgs.entrustType = this.entrustType;
        oneYearArgs.clientId = this.clientId;
        this.fetchData(oneYearArgs);
      },
      fetchData(args){
        var self = this;
        RemoteDAO.callJCL30000(args, function (response) {
          self.test = JSON.stringify(args) + JSON.stringify(response)
          if (response.error == "0") {
            var dateArray = [];
            var myArray = [];
            var indexArray = [];

            var data = response.data.body.data;
            data = data.sort(self.compare('date'));//根据date排序
            if (data.length == 0) {
              myArray.push("");
              indexArray.push("");
              dateArray.push("");
            } else {
              data = data.sort(self.compare('date'));//根据date排序
              _.each(data, function (item, index) {
                myArray.push(CommonUtil.toFixed(item.rate, 2));//我的或组合收益
                indexArray.push(CommonUtil.toFixed(item.rate300, 2));//沪深300收益
                dateArray.push(CommonUtil.formatDatePoint(item.date)); //时间轴数组
              });
            }

            var prefix = "";
            if (self.entrustType == '2') {
              prefix = "组合";
            } else if (args.userType == Constant.user.OTHER) {
              prefix = "TA的收益";
            } else {
              prefix = "我的收益";
            }

            var chartData = {
              labels: dateArray,
              datasets: [
                {
                  label: prefix,
                  fillColor: "rgba(220,220,220,0.2)",
                  strokeColor: "#FF4F4F",
                  pointColor: "#FF4F4F",
                  pointStrokeColor: "#fff",
                  pointHighlightFill: "#fff",
                  pointHighlightStroke: "rgba(220,220,220,1)",
                  data: myArray
                },
                {
                  label: "沪深300",
                  fillColor: "rgba(196,219,234,0.2)",
                  strokeColor: "#C4DBEA",
                  pointColor: "#C4DBEA",
                  pointStrokeColor: "#fff",
                  pointHighlightFill: "#fff",
                  pointHighlightStroke: "rgba(151,187,205,1)",
                  data: indexArray
                }
              ]
            };

            if (self.entrustType == '1' && args.dataType == "0") { //个人3个月
              self.threeMonthData = chartData;
              self.createChart(self.threeMonthData);//默认调接口取数据时只渲染3个月的图
              if (args.userType == Constant.user.OTHER) {  // 更新分享页数据
                var shareOtherDetails = LocalDAO.getShareOtherDetails();
                shareOtherDetails.chart.threeMonth = chartData;
                LocalDAO.setShareOtherDetails(shareOtherDetails);
              } else {
                var shareSelfDetails = LocalDAO.getShareSelfDetails();
                shareSelfDetails.chart.threeMonth = chartData;
                LocalDAO.setShareSelfDetails(shareSelfDetails);
              }
            } else if (self.entrustType == '1' && args.dataType == "1") { //个人一年
              self.oneYearData = chartData;
              // 更新分享页数据
              if (args.userType == Constant.user.OTHER) {
                var shareOtherDetails = LocalDAO.getShareOtherDetails();
                shareOtherDetails.chart.oneYear = chartData;
                LocalDAO.setShareOtherDetails(shareOtherDetails);
              } else {
                var shareSelfDetails = LocalDAO.getShareSelfDetails();
                shareSelfDetails.chart.oneYear = chartData;
                LocalDAO.setShareSelfDetails(shareSelfDetails);
              }

            } else if (self.entrustType == '2' && args.dataType == "0") { //组合3个月
              self.threeMonthData = chartData;
              self.createChart(self.threeMonthData);//默认调接口取数据时只渲染3个月的图

              // 更新分享页数据
              var shareGroup = LocalDAO.getShareGroup();
              shareGroup.optionMonth = chartData;
              LocalDAO.setShareGroup(shareGroup);
            } else if (self.entrustType == '2' && args.dataType == "1") { //组合1年
              self.oneYearData = chartData;
              // 更新分享页数据
              var shareGroup = LocalDAO.getShareGroup();
              shareGroup.optionYear = chartData;
              LocalDAO.setShareGroup(shareGroup);

            }

          } else {
            self.showCanvas = false;
            self.error = response.data;
          }
        });
      },
      compare(propertyName){
        return function (object1, object2) {
          var value1 = object1[propertyName];
          var value2 = object2[propertyName];
          if (value2 < value1) {
            return 1;
          } else if (value2 > value1) {
            return -1;
          } else {
            return 0;
          }
        }
      }
    }
  }
</script>

<style scoped>

</style>
